﻿/// 7. Write a program that replaces all occurrences of the substring "start" with the substring "finish" in a text file. 
/// Ensure it will work with large files (e.g. 100 MB).
/// 8. Modify the solution of the previous problem to replace only whole words (not substrings).

using System;
using System.IO;
using System.Text.RegularExpressions;


namespace c_sh_II_lek_6_files
{
    class zad7_8
    {
        static void Main()
        {
            string input = @"..\..\input.txt";
            string output = @"..\..\output.txt";
            bool wholeWordOnly = true; // change to toggle between task 8 and 7

            if (File.Exists(output))
            {
                File.Delete(output);
            }

            /// tank you stackoverflow ;)...
            using (FileStream fs = new FileStream(input, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (BufferedStream bs = new BufferedStream(fs))
                {
                    using (StreamReader _in = new StreamReader(bs))
                    {
                        using (StreamWriter _out = new StreamWriter(output))
                        {
                            string line;
                            while ((line = _in.ReadLine()) != null)
                            {
                                if (wholeWordOnly)
                                {
                                    _out.WriteLine(Regex.Replace(line, @"\bstart\b", "finish")); 
                                }
                                else
                                {
                                    _out.WriteLine(line.Replace("start", "finish"));
                                }
                            }
                        }
                    }  
                }
            }
        }
    }
}
